package com.etoak.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.properties.ImageProperties;
import com.etoak.common.core.vo.ResultVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    ImageProperties imageProperties;

    @PostMapping("/image")
    public ResultVO<String> upload(MultipartFile pic) throws IOException {
        if(ObjectUtils.isEmpty(pic)||pic.isEmpty()) {
            return ResultVO.failed("文件不能为空");
        }
        if(!imageProperties.getTypes().contains(pic.getContentType())){
            String types = imageProperties.getTypes().stream().map(typess -> typess.substring(typess.lastIndexOf("/") + 1))
                    .collect(Collectors.joining(","));
            return ResultVO.failed("仅支持"+types+"类型的文件");
        }
        String fileName= IdUtil.simpleUUID()+"."+ FileNameUtil.getSuffix(pic.getOriginalFilename());

        File ff = new File(imageProperties.getUploadDir());
        if(!ff.exists()) {
            ff.mkdirs();
        }
        //目标文件
        File file = new File(ff,fileName);
        //上传文件
        pic.transferTo(file);

        String path = imageProperties.getMapping().endsWith("/")?
                imageProperties.getMapping()+fileName:imageProperties.getMapping()+"/"+fileName;

        return ResultVO.success(path);

    }

}
